package com.techgene.kanban.controller;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;




import com.techgene.kanban.domain.Project;
import com.techgene.kanban.domain.RequestParamUser;
import com.techgene.kanban.domain.User;
import com.techgene.kanban.exception.KBDaoException;
import com.techgene.kanban.exception.KBException;
import com.techgene.kanban.exception.KBServiceException;
import com.techgene.kanban.service.UserService;
import com.techgene.kanban.util.AppConstants;



/**
 * adding UserDetails
 * AddUser Handler
 * @author TechGene
 */
@Controller
public class UserController 
{
	
	
	private Logger logger = LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	UserService addUserService;

	
	@Autowired 
	DataSource dataSource;
	
	
	
	
	
	/**
	 * shows addUser.jsp
	 * @param flashData RedirectAttributes
	 * @param model Model
	 * @return
	 */
	@RequestMapping(value = "/admin/addUser", method = RequestMethod.GET)
	public ModelAndView showAddUserPage(RedirectAttributes flashData, Model model)
	{
		logger.debug(">> showAddUserPage");
		String viewName = AppConstants.ADD_USER_PAGE;

		try{
			
			model.addAttribute("command",new RequestParamUser());
			
		   }catch(Exception e) {
			    
			   logger.error(e.getMessage());
			   flashData.addFlashAttribute("errorMsg",e.getMessage());
			   viewName=AppConstants.COMMON_ERROR_PAGE;
		   }
		
		logger.debug("<< showAddUserPage");
		return new ModelAndView(viewName);
	}
	
	
	
	
	
	
	/**
	 * submitting the details of users
	 * @param flashData RedirectAttributes
	 * @param ModelAttribute userData
	 * @return
	 */
	@RequestMapping(value = "/admin/addUser", method = RequestMethod.POST)
	public RedirectView submitAddUserPage( @ModelAttribute RequestParamUser userData , RedirectAttributes flashData)
	{
		logger.debug(">> submitAddUserPage [userData = {}]",userData);
		
		String result =null;
		String viewName=AppConstants.LOGIN_PAGE;
		
		try
		{
				User profile = new User();
				profile.setUsername(userData.getUsername());
				profile.setPassword(userData.getPassword());
				profile.setFirstName(userData.getFirstName());
				profile.setLastName(userData.getLastName());
				profile.setEmail(userData.getEmail());
				profile.setRole(userData.getRole());
				
				
				/*
				 * calling addUserData method in addUserServiceImpl to store the User Details
				 */
				result = addUserService.addUserData(profile);
			    logger.debug("result={}",result);
			    
			    
			    /*
				 * checks the result status to know whether user details are successfully added or not
				 */
				if(result.equalsIgnoreCase("success"))
				{
					flashData.addFlashAttribute("statusMsg",AppConstants.ADD_USER_DATA_SUCCESS);
				}else {
					
				    flashData.addFlashAttribute("statusMsg",AppConstants.ADD_USER_DATA_FAILURE);
			    }
			
		}catch(KBServiceException e) {
			
			logger.error(e.getMessage(),e);
			flashData.addFlashAttribute("statusMessage",AppConstants.ADD_USER_DATA_FAILURE );
			return new RedirectView(viewName);
			
		}catch(Exception e)
		{
			logger.error(e.getMessage(),e);
			flashData.addFlashAttribute("statusMessage",AppConstants.ADD_USER_DATA_FAILURE );
			return new RedirectView(viewName);
		}
		
		logger.debug("<< submitAddUserPage");
		return new RedirectView(viewName);
		
	}
	
	
	
	
	
	/**
	 * shows updateDeleteUser.jsp
	 * @param flashData RedirectAttributes
	 * @param model Model
	 * @return
	 */
	
	@RequestMapping(value = "/admin/updateDeleteUser", method = RequestMethod.GET)
	public ModelAndView showUpdateDeleteUserPage(RedirectAttributes flashData, Model model)
	{
		logger.debug(">> showUpdateDeleteUserPage");
		String viewName = AppConstants.UPDATE_DELETE_USER_PAGE;

		try{
				
			model.addAttribute("command",new RequestParamUser());
				
		}catch(Exception e) {
				    
			logger.error(e.getMessage());
			flashData.addFlashAttribute("errorMsg",e.getMessage());
			viewName=AppConstants.UPDATE_DELETE_USER_ERROR;
		}
			
		logger.debug("<< showUpdateDeleteUserPage");
		return new ModelAndView(viewName);
	}
		
		
		
		
		
	/**
	* fetchs username firstname,lastname,emil,role for the selected user
	* @param userName
	* @param map
	* @param flashdata RedirectAttribute
	* @return
	* @throws KBServiceException
	* @throws KBDaoException
	*/
		
	@RequestMapping(value="/admin/fetchUserDetails", method = RequestMethod.POST)
	public ModelAndView submitUpdateDeleteUserPage(@ModelAttribute RequestParamUser userData,@RequestParam String userName,RedirectAttributes flashData, Model model)throws KBServiceException, KBDaoException
	{
			

		logger.debug(">> submitUpdateDeleteUserPage , users={}", userName);
		ModelAndView returnView = null;
		User user;
		
		try{
				
			user =(User)addUserService.fetchUserDetails(userName);	
			model.addAttribute("command", new User());
			model.addAttribute("userName", userName);
			returnView = new ModelAndView(AppConstants.SHOW_USER_DETAILS_PAGE,"user",user);
			logger.debug("profile={}",user);
				 
				
		}catch (KBServiceException e) {
				
			logger.error(e.getMessage(), e);
			flashData.addAttribute("errorMsg",AppConstants.FECTH_USER_DETAILS_FAILURE);
			returnView = new ModelAndView(new RedirectView(AppConstants.COMMON_ERROR_PAGE));
			
		}catch (Exception e) {
				
			logger.error(e.getMessage(), e);
			flashData.addAttribute("errorMsg",AppConstants.FECTH_USER_DETAILS_FAILURE);
			returnView = new ModelAndView(new RedirectView(AppConstants.COMMON_ERROR_PAGE));
				
		}
			
		logger.debug("<< submitUpdateDeleteUserPage");
		return returnView;
			
			
	}
		
		

		
	/**
	* updating user details
	* @param request
	* @param map
	* @param flashData RedirectAttributes
	* @return
	* @throws KBException
	*/
	@RequestMapping(value="/admin/updation", method = RequestMethod.POST, params="operation=Update")
	public RedirectView submitUpdateDeleteUserPage(@ModelAttribute("user") User profile, RedirectAttributes flashData, Model model)throws KBDaoException,KBServiceException
	{
			
		logger.debug(">> submitUpdateDeleteUserPage , userDetails = [ {} ]", profile);
		RedirectView returnView=null;
			
		try{
				
			String result= addUserService.updateUserDetails(profile);
			logger.debug("result= {} ",result);
			flashData.addFlashAttribute("statusMsg",AppConstants.UPDATE_USER_DETAILS_SUCCESS);
			returnView = new RedirectView(AppConstants.LOGIN_PAGE);
				
		}catch (KBServiceException e) {
				
			logger.error(e.getMessage(), e);
			flashData.addAttribute("errorMsg",AppConstants.DELETE_USER_DETAILS_FAILURE);
			returnView = new RedirectView(AppConstants.UPDATE_DELETE_USER_ERROR);
				
		}catch (Exception e) {
				
			logger.error(e.getMessage(), e);
			flashData.addAttribute("errorMsg",AppConstants.DELETE_USER_DETAILS_FAILURE);
			returnView = new RedirectView(AppConstants.UPDATE_DELETE_USER_ERROR);
				
		}
			
		logger.debug("<< submitUpdateDeleteUserPage , userDetails = [ {} ]", profile);
		return returnView;

		
	}
		

		
		
		
		
	/**
	* deleting user details
	* @param request
	* @param map
	* @param flashData RedirectAttributes
	* @return
	* @throws KBException
	*/
	@RequestMapping(value="/admin/updation", method = RequestMethod.POST, params="operation=Delete")
	public RedirectView submitUpdateDeleteUserPage(@ModelAttribute User profile,@RequestParam String username, RedirectAttributes flashData, Model map)throws KBDaoException, KBServiceException
	{
			
		logger.debug(">> submitUpdateDeleteUserPage ", username);
		RedirectView returnView=null;
			
		try{
				
			String result = addUserService.deleteUserDetails(username);
			logger.debug("result={}",result);
			flashData.addFlashAttribute("statusMsg",AppConstants.DELETE_USER_DETAILS_SUCCESS);
			returnView = new RedirectView(AppConstants.LOGIN_PAGE);
				
		}catch (KBServiceException e) {
				
			logger.error(e.getMessage(), e);
			flashData.addAttribute("errorMsg",AppConstants.DELETE_USER_DETAILS_FAILURE);
			returnView = new RedirectView(AppConstants.UPDATE_DELETE_USER_ERROR);
				
		}catch (Exception e) {
				
			logger.error(e.getMessage(), e);
			flashData.addAttribute("errorMsg",AppConstants.DELETE_USER_DETAILS_FAILURE);
			returnView = new RedirectView(AppConstants.UPDATE_DELETE_USER_ERROR);
				
		}
			
		logger.debug("<< submitUpdateDeleteUserPage ", username);
		return returnView;
	}
	
}




